﻿using Dm.filter.log;
using WH.Model.Systems;
using WH.Repositories.IRepositories.ISystem;
using WH.Services.BaseService;
using WH.Services.IServices.ISystem;
using WH.Common.Constant;
using SqlSugar;

namespace WH.Services.Services.System
{
    public class RolePermissionService : BaseService<RolePermissionEntity>, IRolePermissionService
    {
        private readonly IRolePermissionRepository _permissionRepository;
        private readonly IRoleService _roleService;
        public RolePermissionService(IRolePermissionRepository rolePermissionRepository, IRoleService roleService) : base(rolePermissionRepository)
        {
            _permissionRepository = rolePermissionRepository;
            _roleService = roleService;
        }

        public async Task<IEnumerable<RolePermissionEntity>> GetPermissionResource(string roleId, params int?[] ResourceTypes)
        {
            var roles = await _roleService.FindAllAsync(x => x.IsEnable, true);

            var role = roles.FirstOrDefault(x => x.Id == roleId);

            if (role is null)
            {
                return new List<RolePermissionEntity>();
            }

            var exp = Expressionable.Create<RolePermissionEntity>();

            exp.And(x => x.IsEnable);

            if (role.TypeCode != BusinessFunction.TopParentId)
            {
                exp.And(x => x.RoleId == roleId);
            }

            if (ResourceTypes.Length > 0)
            {
                exp.And(x => ResourceTypes.Contains(x.ResourceType));
            }
            var permiss = await this.FindAllAsync(exp.ToExpression(), true); ;

            return permiss;
        }
    }
}
